/**axios封装
 * 请求拦截、相应拦截、错误统一处理
 */
import axios from 'axios';
import QS from 'qs';
import { GET, POST } from "./config";
import { ElMessageBox } from 'element-plus'
import router from '@/router/index.ts'

axios.defaults.baseURL = import.meta.env.VITE_API;

// 请求拦截器
axios.interceptors.request.use(
    async config => {
        const token = localStorage.getItem('token');
        config.headers['accessToken'] = token
        return config;
    },
    error => {
        return Promise.error(error);
    })

let isRefreshing = false;
// 响应拦截器
axios.interceptors.response.use(
    response => {
        const res = response.data
        const { code } = res
        if (code === 200) {
            return Promise.resolve(response);
        } else if (code === 401) {
            // 检查是否已经在处理中，如果不是则显示弹窗
            if (!isRefreshing) {
                isRefreshing = true; // 设置为正在处理
                ElMessageBox.confirm(res.message, '去登录', {
                    confirmButtonText: '登录',
                    cancelButtonText: '关闭',
                    type: 'warning'
                }).then(() => {
                    router.push('/')
                    localStorage.removeItem('token')
                }).catch(() => {
                    router.push('/')
                    localStorage.removeItem('token')
                }).finally(() => {
                    isRefreshing = false; // 处理完成后重置标记
                })
            }
            return Promise.reject(response); // 始终返回reject，避免请求被认为成功
        } else {
            return Promise.reject(response);
        }
    },
    error => {
        if (error.response.status) {
            switch (error.response.status) {
                case 401:
                    break
                case 403:
                    router.push('/')
                    localStorage.removeItem('token')
                case 404:
                    break;
                default:
            }
            return Promise.reject(error.response);
        }

    }
);

/**
 * GET请求
 * @param {String} url 
 * @param {Object} params 查询参数（拼接到URL）
 */
const get = (url, params) => {
    const queryString = QS.stringify(params);
    const fullUrl = queryString ? `${url}?${queryString}` : url;

    return new Promise((resolve, reject) => {
        axios.get(fullUrl)
            .then(res => resolve(res))
            .catch(err => reject(err))
    });
}

/**
 * POST请求
 * @param {String} url 
 * @param {Object} params 包含：
 *   - queryParams: URL查询参数（拼接到URL）
 *   - bodyParams: 请求体参数
 * @param {Object} config 请求配置
 */
const post = (url, params = {}, config = {}) => {
    // 分离URL参数和请求体参数
    const { queryParams = {}, bodyParams = {} } = params;
    
    // 处理URL参数拼接
    const queryString = QS.stringify(queryParams);
    const fullUrl = queryString ? `${url}?${queryString}` : url;
    
    // 处理请求体参数
    const requestData = config?.headers?.['Content-Type'] === 'application/x-www-form-urlencoded' 
        ? QS.stringify(bodyParams) 
        : bodyParams;

    return new Promise((resolve, reject) => {
        axios.post(fullUrl, requestData, config)
            .then(res => resolve(res))
            .catch(err => reject(err))
    });
}

export function requestT(method, url, params = {}, config = {}) {
    switch (method) {
        case GET:
            return get(url, params);
        case POST:
            return post(url, params, config);
        default:
            throw new Error(`Unsupported method: ${method}`);
    }
}